<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-card" shadow="hover">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="选择工单类型" clearable>
            <el-option label="设备故障" value="device_failure" />
            <el-option label="漏水问题" value="water_leakage" />
            <el-option label="水表故障" value="meter_malfunction" />
            <el-option label="管道问题" value="pipeline_issue" />
            <el-option label="其他问题" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="选择工单状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已派发" value="assigned" />
            <el-option label="处理中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="工单描述、设备ID、站点ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card pending" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.pending }}</div>
                <div class="stat-label">待处理</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card assigned" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.assigned }}</div>
                <div class="stat-label">已派发</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card in-progress" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Tools /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.inProgress }}</div>
                <div class="stat-label">处理中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card completed" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon><Check /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 工单列表 -->
    <el-card class="workorder-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">工单列表</span>
          <div class="header-actions">
            <el-button type="info" icon="DataAnalysis" @click="goToStatistics">统计报表</el-button>
            <el-button type="success" icon="Plus" @click="handleCreate">创建工单</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="workorderList"
        highlight-current-row
        row-key="id"
        class="workorder-table"
      >
        <el-table-column label="工单编号" prop="id" width="100" align="center" />
        
        <el-table-column label="工单类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)" size="small">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="工单状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="设备ID" prop="deviceId" width="100" align="center" />
        <el-table-column label="站点ID" prop="siteId" width="100" align="center" />
        
        <el-table-column label="工单描述" prop="description" min-width="200" show-overflow-tooltip />
        
        <el-table-column label="创建时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>

        <el-table-column label="完成时间" width="160" align="center">
          <template #default="scope">
            {{ scope.row.finishedAt ? formatDateTime(scope.row.finishedAt) : '-' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 'pending'"
              type="primary"
              link
              size="small"
              icon="User"
              @click="handleAssign(scope.row)"
            >
              派发
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'assigned' || scope.row.status === 'in_progress'"
              type="warning"
              link
              size="small"
              icon="Tools"
              @click="handleUpdateStatus(scope.row)"
            >
              更新状态
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'in_progress'"
              type="success"
              link
              size="small"
              icon="Check"
              @click="handleComplete(scope.row)"
            >
              完成
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'completed' && !scope.row.evaluation"
              type="info"
              link
              size="small"
              icon="Star"
              @click="handleEvaluate(scope.row)"
            >
              评价
            </el-button>
            
            <el-button
              type="primary"
              link
              size="small"
              icon="View"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            
            <el-button
              type="primary"
              link
              size="small"
              icon="Edit"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="queryParams.current"
          :page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑工单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="workorderFormRef"
        :model="workorderForm"
        :rules="workorderRules"
        label-width="100px"
      >
        <el-form-item label="工单类型" prop="type">
          <el-select v-model="workorderForm.type" placeholder="选择工单类型" style="width: 100%">
            <el-option label="设备故障" value="device_failure" />
            <el-option label="漏水问题" value="water_leakage" />
            <el-option label="水表故障" value="meter_malfunction" />
            <el-option label="管道问题" value="pipeline_issue" />
            <el-option label="其他问题" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="workorderForm.deviceId" placeholder="请输入设备ID" />
        </el-form-item>
        
        <el-form-item label="站点ID" prop="siteId">
          <el-input v-model="workorderForm.siteId" placeholder="请输入站点ID" />
        </el-form-item>
        
        <el-form-item label="工单描述" prop="description">
          <el-input
            v-model="workorderForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述工单问题"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 派发工单对话框 -->
    <el-dialog v-model="assignDialogVisible" title="派发工单" width="400px">
      <el-form :model="assignForm" label-width="80px">
        <el-form-item label="指派人">
          <el-select v-model="assignForm.assigneeId" placeholder="选择指派人" style="width: 100%">
            <el-option label="张三" value="1" />
            <el-option label="李四" value="2" />
            <el-option label="王五" value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="assignDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 完成工单对话框 -->
    <el-dialog v-model="completeDialogVisible" title="完成工单" width="500px">
      <el-form :model="completeForm" label-width="80px">
        <el-form-item label="完成描述">
          <el-input
            v-model="completeForm.description"
            type="textarea"
            :rows="4"
            placeholder="请描述工单完成情况"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="completeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCompleteSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 评价工单对话框 -->
    <el-dialog v-model="evaluateDialogVisible" title="评价工单" width="500px">
      <el-form :model="evaluateForm" label-width="80px">
        <el-form-item label="评价内容">
          <el-input
            v-model="evaluateForm.evaluation"
            type="textarea"
            :rows="4"
            placeholder="请对工单处理情况进行评价"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="evaluateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEvaluateSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 更新工单状态对话框 -->
    <el-dialog v-model="statusDialogVisible" title="更新工单状态" width="500px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="工单状态">
          <el-select v-model="statusForm.status" placeholder="请选择状态" style="width: 100%;">
            <el-option label="待处理" value="pending" />
            <el-option label="已派发" value="assigned" />
            <el-option label="处理中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleStatusSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, User, Tools, Check, Search, Refresh, Plus, View, Edit, Star, DataAnalysis } from '@element-plus/icons-vue'
import WorkOrderAPI from '@/api/system/workorder.api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const workorderList = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const assignDialogVisible = ref(false)
const completeDialogVisible = ref(false)
const evaluateDialogVisible = ref(false)
const statusDialogVisible = ref(false)

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  type: '',
  status: '',
  keywords: ''
})

// 工单表单
const workorderForm = reactive({
  id: null,
  type: '',
  deviceId: '',
  siteId: '',
  description: ''
})

// 派发表单
const assignForm = reactive({
  workOrderId: null,
  assigneeId: ''
})

// 完成表单
const completeForm = reactive({
  workOrderId: null,
  description: ''
})

// 评价表单
const evaluateForm = reactive({
  workOrderId: null,
  evaluation: ''
})

// 状态更新表单
const statusForm = reactive({
  workOrderId: null,
  status: ''
})

// 统计数据
const stats = reactive({
  pending: 0,
  assigned: 0,
  inProgress: 0,
  completed: 0
})

// 表单校验规则
const workorderRules = {
  type: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
  deviceId: [{ required: true, message: '请输入设备ID', trigger: 'blur' }],
  siteId: [{ required: true, message: '请输入站点ID', trigger: 'blur' }],
  description: [{ required: true, message: '请输入工单描述', trigger: 'blur' }]
}

// 计算属性
const dialogTitle = computed(() => {
  return workorderForm.id ? '编辑工单' : '创建工单'
})

// 方法
const handleQuery = async () => {
  loading.value = true
  try {
    const result = await WorkOrderAPI.getPage(queryParams)
    workorderList.value = result.records
    total.value = result.total
    updateStats()
  } catch (error) {
    ElMessage.error('查询工单列表失败')
  } finally {
    loading.value = false
  }
}

const handleResetQuery = () => {
  Object.assign(queryParams, {
    current: 1,
    size: 10,
    type: '',
    status: '',
    keywords: ''
  })
  handleQuery()
}

const handleSizeChange = (size) => {
  queryParams.size = size
  queryParams.current = 1
  handleQuery()
}

const handleCurrentChange = (current) => {
  queryParams.current = current
  handleQuery()
}

const handleCreate = () => {
  Object.assign(workorderForm, {
    id: null,
    type: '',
    deviceId: '',
    siteId: '',
    description: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  Object.assign(workorderForm, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  try {
    if (workorderForm.id) {
      // 编辑
      await WorkOrderAPI.update(workorderForm.id, workorderForm)
      ElMessage.success('编辑工单成功')
    } else {
      // 创建
      await WorkOrderAPI.create(workorderForm)
      ElMessage.success('创建工单成功')
    }
    dialogVisible.value = false
    handleQuery()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleAssign = (row) => {
  assignForm.workOrderId = row.id
  assignForm.assigneeId = ''
  assignDialogVisible.value = true
}

const handleAssignSubmit = async () => {
  try {
    await WorkOrderAPI.assign(assignForm.workOrderId, assignForm.assigneeId)
    ElMessage.success('派发工单成功')
    assignDialogVisible.value = false
    handleQuery()
  } catch (error) {
    ElMessage.error('派发工单失败')
  }
}

const handleUpdateStatus = (row) => {
  statusForm.workOrderId = row.id
  statusForm.status = row.status
  statusDialogVisible.value = true
}

const handleComplete = (row) => {
  completeForm.workOrderId = row.id
  completeForm.description = ''
  completeDialogVisible.value = true
}

const handleCompleteSubmit = async () => {
  try {
    await WorkOrderAPI.complete(completeForm.workOrderId, completeForm.description)
    ElMessage.success('完成工单成功')
    completeDialogVisible.value = false
    handleQuery()
  } catch (error) {
    ElMessage.error('完成工单失败')
  }
}

const handleEvaluate = (row) => {
  evaluateForm.workOrderId = row.id
  evaluateForm.evaluation = ''
  evaluateDialogVisible.value = true
}

const handleEvaluateSubmit = async () => {
  try {
    await WorkOrderAPI.evaluate(evaluateForm.workOrderId, evaluateForm.evaluation)
    ElMessage.success('评价工单成功')
    evaluateDialogVisible.value = false
    handleQuery()
  } catch (error) {
    ElMessage.error('评价工单失败')
  }
}

const handleStatusSubmit = async () => {
  try {
    await WorkOrderAPI.updateStatus(statusForm.workOrderId, statusForm.status)
    ElMessage.success('更新工单状态成功')
    statusDialogVisible.value = false
    handleQuery()
  } catch (error) {
    ElMessage.error('更新工单状态失败')
  }
}

const handleView = (row) => {
  // 查看工单详情 - 添加 /system 前缀
  router.push(`/system/workorder/detail/${row.id}`)
}

const goToStatistics = () => {
  router.push('/system/workorder/statistics')
}

const updateStats = () => {
  stats.pending = workorderList.value.filter(item => item.status === 'pending').length
  stats.assigned = workorderList.value.filter(item => item.status === 'assigned').length
  stats.inProgress = workorderList.value.filter(item => item.status === 'in_progress').length
  stats.completed = workorderList.value.filter(item => item.status === 'completed').length
}

const getTypeLabel = (type) => {
  const typeMap = {
    'device_failure': '设备故障',
    'water_leakage': '漏水问题',
    'meter_malfunction': '水表故障',
    'pipeline_issue': '管道问题',
    'other': '其他问题'
  }
  return typeMap[type] || type
}

const getTypeTagType = (type) => {
  const typeMap = {
    'device_failure': 'danger',
    'water_leakage': 'warning',
    'meter_malfunction': 'info',
    'pipeline_issue': 'error',
    'other': ''
  }
  return typeMap[type] || ''
}

const getStatusLabel = (status) => {
  const statusMap = {
    'pending': '待处理',
    'assigned': '已派发',
    'in_progress': '处理中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'assigned': 'info',
    'in_progress': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || ''
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.search-form {
  margin-bottom: 0;
}

.stats-container {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stat-card.pending .stat-icon {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.stat-card.assigned .stat-icon {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-card.in-progress .stat-icon {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.stat-card.completed .stat-icon {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.workorder-card {
  border-radius: 12px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.workorder-table {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-card) {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-select) {
  border-radius: 6px;
}
</style>
